import React, { PureComponent } from "react";
import { connect } from "dva";
import { Card, Divider, Table, Switch, Popconfirm } from "antd";
import { openNotificationWithIcon } from "utils/comm";
import PageLayout from "components/pageconlayout/PageLayout";
import QueryExtra from "./components/QueryExtra";
import CardTitle from "./components/CardTitle";
import CreateForm from "./components/CreateForm";
import Detail from "./components/Detail";
// import { MockData } from "./components/MockData";
import styles from "./index.less";

@connect(({ channel, loading }) => ({
  channelStore: channel,
  loading,
}))
class channelManagement extends PureComponent {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.state = {
      visible: false,
      channelList: [],
      page: {
        pageNum: 1,
        pageSize: 6,
      },
    };
  }

  componentDidMount() {
    this.initData();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: "channel/clearData" });
  }

  getColumns = () => {
    const columns = [
      {
        title: "序号",
        dataIndex: "id",
        render: (text, record) => {
          const str = record.generatedOrderNum;
          return <span>{str}</span>;
        },
      },
      {
        title: "渠道编号",
        dataIndex: "channelCode",
      },
      {
        title: "渠道名称",
        dataIndex: "channelName",
      },
      {
        title: "启用状态",
        dataIndex: "channelStatus",
        render: (text, record) => (
          <Switch
            defaultChecked
            onChange={() => this.handleSwitchChange(record)}
            checked={Boolean(record.channelStatus)}
            size="small"
          />
        ),
      },
      {
        title: "操作",
        dataIndex: "opration",
        // eslint-disable-next-line no-unused-vars
        render: (text, record) => {
          return (
            <div>
              <a
                onClick={(e) => {
                  e.preventDefault();
                  this.handleDetailVisible(true, record);
                }}
              >
                查看
              </a>
              <Divider type="vertical" />
              <a
                onClick={(e) => {
                  e.preventDefault();
                  this.handleCreateVisible(true, record);
                }}
              >
                编辑
              </a>
              <Divider type="vertical" />
              <Popconfirm
                placement="left"
                title={`确定删除渠道：${record.channelName}?`}
                onConfirm={() => {
                  this.handleDel(record);
                }}
                okText="确定"
                cancelText="取消"
              >
                <a
                  onClick={(e) => {
                    e.preventDefault();
                  }}
                >
                  删除
                </a>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    return columns;
  };

  getFormThis = (formThis, type = "advancedFilter") => {
    if (type === "queryExtra") {
      this.queryExtraForm = formThis;
    }
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    return { ...this.searchParams, pageNum, pageSize };
  };

  // 操作-启用
  handleSwitchChange = (record) => {
    const { id, channelStatus } = record;
    const { dispatch } = this.props;
    dispatch({
      type: "channel/startStatus",
      payload: { id, channelStatus: !channelStatus },
    }).then((resp) => {
      const { errortext, errCode } = resp;
      if (errCode === 0) {
        this.initData();
        this.openNotificationWithIcon("success", "", errortext || "操作成功");
      } else {
        this.openNotificationWithIcon("warning", "", errortext || "操作失败");
      }
    });
  };

  // 触发查询
  initData = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParam();
    dispatch({ type: "channel/getChannelList", payload: params }).then(
      (resp) => {
        if (resp) {
          const {
            datas,
            pageNum: _pageNum,
            totalCount: total,
            pageSize,
          } = resp;
          const reOrderData = this.generateOrderNum(datas, total);
          if (_pageNum > 1 && reOrderData.length === 0) {
            const newState = { page: { pageNum: _pageNum - 1, pageSize } };
            this.setState(newState, () => {
              this.initData();
            });
          } else {
            this.setState({
              channelList: reOrderData,
            });
          }
        }
      },
    );
  };

  generateOrderNum = (list) => {
    if (!Array.isArray(list)) {
      return [];
    }
    const {
      page: { pageNum, pageSize },
    } = this.state;
    const { length } = list;
    for (let i = 0; i < length; i += 1) {
      const item = list[i];
      const generatedOrderNum = pageSize * (pageNum - 1) + i + 1;
      item.generatedOrderNum = generatedOrderNum;
    }
    return list;
  };

  // 页码页数改变
  handlePageChange = ({ current: pageNum, pageSize }) => {
    this.setState({ page: { pageNum, pageSize } }, () => {
      this.initData();
    });
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    if (this.queryExtraForm) this.queryExtraForm.handleSubmit();
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  // 查询参数改变
  handleParamsChange = (newparams) => {
    this.searchParams = { ...this.searchParams, ...newparams };
  };

  // 创建渠道
  handleCreateVisible = (visible, record = "", isQuery = false) => {
    this.record = record;
    this.title = "新增渠道";
    if (record) this.title = "编辑渠道";
    if (this.isLeaf) return;
    this.setState({ visible });
    if (isQuery) {
      this.handleSearch();
    }
  };

  // 模板详情
  handleDetailVisible = (visible, record = "") => {
    this.record = record;
    this.title = "模板详情";
    if (this.isLeaf) return;
    this.setState({ detailVisible: visible });
  };

  // 删除通知模板
  handleDel = (record = {}) => {
    if (!record.id) return;
    const { dispatch } = this.props;
    dispatch({
      type: "channel/deleteChannel",
      payload: { id: record.id },
    }).then((resp) => {
      const { errCode, errortext } = resp;
      if (errCode === 0) {
        this.handleSearch();
        this.openNotificationWithIcon("success", "", errortext || "删除成功");
      } else {
        this.openNotificationWithIcon("warning", "", errortext || "删除失败");
      }
    });
  };

  render() {
    const {
      page: { pageNum, pageSize },
      visible,
      detailVisible,
      channelList = [],
    } = this.state;
    const { channelStore, loading, dispatch } = this.props;
    const { totalCount = 0 } = channelStore;

    const listLoading = loading.effects["channel/getChannelList"];
    const createLoading = loading.effects["channel/addChannel"] || false;
    const editLoading = loading.effects["channel/editChannel"] || false;
    return (
      <div className={styles.root}>
        <PageLayout
          leftContent={null}
          rightContent={
            <Card
              title={
                <CardTitle
                  total={totalCount}
                  handleCreateVisible={this.handleCreateVisible}
                  addVisible="true"
                />
              }
              extra={
                <QueryExtra
                  handleParamsChange={this.handleParamsChange}
                  onSearch={this.handleSearch}
                  getFormThis={this.getFormThis}
                />
              }
              bodyStyle={{
                minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
              }}
              style={{ width: "100%" }}
            >
              <Table
                columns={this.getColumns()}
                dataSource={channelList}
                rowKey="id"
                loading={listLoading}
                className={styles.listcon}
                onChange={this.handlePageChange}
                pagination={{
                  showQuickJumper: true,
                  showSizeChanger: true,
                  pageSizeOptions: ["6", "10", "20", "30"],
                  current: pageNum,
                  pageSize,
                  total: totalCount,
                }}
              />
            </Card>
          }
        />
        {visible && (
          <CreateForm
            title={this.title}
            visible={visible}
            data={this.record}
            handleCreateVisible={this.handleCreateVisible}
            dispatch={dispatch}
            confirmLoading={createLoading || editLoading}
          />
        )}
        {detailVisible && (
          <Detail
            title={this.title}
            visible={detailVisible}
            data={this.record}
            handleDetailVisible={this.handleDetailVisible}
          />
        )}
      </div>
    );
  }
}

export default channelManagement;
